import axios from 'axios'
import type { AxiosInstance, InternalAxiosRequestConfig, AxiosResponse, AxiosRequestConfig } from 'axios'
import { Toast } from 'vant'

// 创建axios实例
const api: AxiosInstance = axios.create({
  baseURL: import.meta.env?.VITE_API_BASE_URL || 'http://localhost:5000/api',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 添加token
    const token = localStorage.getItem('token')
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`
    }
    
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response: AxiosResponse) => {
    const { data } = response
    
    // 如果是文件下载，直接返回
    if (response.config.responseType === 'blob') {
      return response
    }
    
    // 统一处理响应数据
    if (data.success === false) {
      Toast.fail(data.message || '请求失败')
      return Promise.reject(new Error(data.message || '请求失败'))
    }
    
    return data
  },
  (error) => {
    const { response } = error
    
    if (response) {
      const { status, data } = response
      
      switch (status) {
        case 401:
          // 未授权，跳转登录
          Toast.fail('登录已过期，请重新登录')
          localStorage.removeItem('token')
          localStorage.removeItem('user')
          // 这里可以使用router进行跳转，但需要在main.ts中配置
          window.location.href = '/login'
          break
          
        case 403:
          Toast.fail('权限不足')
          break
          
        case 404:
          Toast.fail('请求的资源不存在')
          break
          
        case 500:
          Toast.fail('服务器内部错误')
          break
          
        default:
          Toast.fail(data?.message || `请求失败 (${status})`)
      }
    } else if (error.code === 'ECONNABORTED') {
      Toast.fail('请求超时，请检查网络连接')
    } else {
      Toast.fail('网络错误，请检查网络连接')
    }
    
    return Promise.reject(error)
  }
)

// 封装常用请求方法
export const request = {
  get: <T = any>(url: string, config?: AxiosRequestConfig) => 
    api.get<T>(url, config),
    
  post: <T = any>(url: string, data?: any, config?: AxiosRequestConfig) => 
    api.post<T>(url, data, config),
    
  put: <T = any>(url: string, data?: any, config?: AxiosRequestConfig) => 
    api.put<T>(url, data, config),
    
  delete: <T = any>(url: string, config?: AxiosRequestConfig) => 
    api.delete<T>(url, config),
    
  upload: <T = any>(url: string, formData: FormData, onUploadProgress?: (progressEvent: any) => void) =>
    api.post<T>(url, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      onUploadProgress
    })
}

export default api